// pages/imgCreation/index.js
import utf8Array2Str from 'utf8array2str';

const {
  aiCreationApi
} = require('../../../api/index')
const {
  GPTSHIXIANJIA
} = require('../../../api/config/config')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    logo: "/assets/img/logo_40_40@2.png",
    imgListLength: 0,
    creationImgRes: null, //结果
    requestTask: null,
    timer: null,
    createtitle: '',
    spacetype: '',
    lastId: '', //最后一次通知的id
    top: 0,
    bottom: 0,
    header: {
      Authorization: wx.getStorageSync('token'),
      Accept: 'text/event-stream'
    },
    createImgInfo: null,
    ctx: null,
    childIds: ['loadingCard1', 'loadingCard2', 'loadingCard3', 'loadingCard4'],
    isSuccess: false, //生图结果中是否都生图成功
    title: "排队中...",
    isComplete: false, //创作完成
    showWarnConfirm: false, //退出排队对话框
    isDequeue: false, //是否可以退出队列
    timer: null
  },
  // 退出弹窗
  dialogShow() {
    this.setData({
      showWarnConfirm: true
    })
  },
  // 关闭弹窗
  closeDialog() {
    this.setData({
      showWarnConfirm: false
    })
  },
  // 确认退出
  async dequeue() {
    let _this = this
    let res = await aiCreationApi.dequeue({
      "taskId": wx.getStorageSync('createImgInfo').taskId
    })
    console.log('确认退出', res.statusCode);
    this.setData({
      showWarnConfirm: false
    })
    wx.showToast({
      title: res.message,
      icon: res.statusCode === 200 ? "success" : "none"
    })
    if (res.statusCode === 200) {
      this.setData({
        timer: setTimeout(() => {
          console.log('11111111111111');
          wx.switchTab({
            url: '/pages/ai/index',
            success() {
              _this.setData({
                timer: null
              })
              console.log('timer', _this.data.timer);
            }
          })
        }, 1000)
      })
      // this.data.timer = setInterval(() => {
      //   console.log('11111111111111');
      //   wx.switchTab({
      //     url: '/pages/ai/index',
      //   })
      // }, 1000)
    }
  },
  // 页面跳转
  toPage() {
    wx.navigateTo({
      url: '/pages/ai/creationComplete/index',
    })
  },
  // 继续创作
  toCreate() {
    if (!this.data.isComplete) return
    wx.removeStorageSync('styleStr')
    wx.removeStorageSync('createImgInfo')
    wx.redirectTo({
      url: `/pages/ai/creativeHall/index?type=2&createtitle=${this.data.createtitle}&spacetype=${this.data.spacetype}`,
    })
  },
  // 建立SSE连接
  initSSE() {
    let _this = this
    this.data.requestTask = wx.request({
      url: `${GPTSHIXIANJIA}/sse-notifications`,
      header: _this.data.header,
      enableChunked: true, // enableChunked必须为true
      success: (res) => {
        console.log('连接成功');
      },
      fail: (res) => {
        console.log('连接失败');
        // wx.showToast({
        //   title: '连接失败',
        //   icon: 'none',
        // })
        _this.initSSE() //连接失败重连
      }
    })
    // SSE监听
    this.data.requestTask.onChunkReceived(this.serverResponse)
  },
  // 创建生图任务
  createImg() {
    if (wx.getStorageSync('drawingParameter')) {
      aiCreationApi.creatingImg(wx.getStorageSync('drawingParameter')).then(res => {
        console.log('创建生图任务', res);
        if (res.statusCode === 400) {
          wx.showToast({
            title: '灵感值不足，探索草图里网页端、App，或完成任务获得更多灵感值',
            icon: "none",
            duration: 5000
          })
          this.data.requestTask.offChunkReceived(this.serverResponse)
        }
      }).catch(err => {
        console.log('生图失败', err);
      })
    }
  },
  // 生图状态追踪
  serverResponse(res) {
    // arrayBuffer转string
    let jsonString = utf8Array2Str(new Uint8Array(res.data));
    console.log('jsonString', jsonString);
    // 事件名为createminiimage
    if (jsonString.split('jsonString:')[0].split('event:')[1].split('data')[0].trim() === 'createminiimage') {
      // console.log(jsonString.split('jsonString:')[0].split('event:')[1].split('data')[0]); //event名称
      if (jsonString.includes("data")) {
        this.data.header['last-Event-Id'] = jsonString.split('jsonString:')[0].split('id:')[1].split('event')[0]
        this.data.creationImgRes = JSON.parse(jsonString.split("data:")[1])
        this.setData({
          isDequeue: true
        }) //此时可以退出队列
        console.log('生图状态', this.data.creationImgRes);
        wx.setStorageSync('createImgInfo', {
          ...wx.getStorageSync('createImgInfo'),
          taskId: this.data.creationImgRes?.TaskId
        }) // 保存taskId
        // 生图成功
        if (this.data.creationImgRes.StatusCode === 200) {
          wx.onNetworkStatusChange(this.networkHandler) //关闭网络监听
          wx.setStorageSync('shareImgList', {
            keywords: wx.getStorageSync('drawingParameter')?.forwardDescribe, //可选
            imgList: this.data.creationImgRes.Result.map(item => item.picture_str),
            ratio: wx.getStorageSync('drawingParameter')?.size,
            style: wx.getStorageSync('styleStr')
          })
          // 循环调用子组件方法
          this.data.childIds.forEach((item, index) => {
            this.selectComponent(`#${item}`)?.createImgSuccess(this.data.creationImgRes.Result[index])
          })
          this.setData({
            isSuccess: this.data.creationImgRes.Result.every(item => item.is_safe),
            title: "创作完成",
            isComplete: true
          })
          // this.selectComponent('#loadingCard')?.createImgSuccess(this.data.creationImgRes.Result)
          // wx.redirectTo({
          //   url: `/pages/ai/creationComplete/index?type=1&createtitle=${this.data.createtitle}&spacetype=${this.data.spacetype}`,
          // }) 
        }
        if (this.data.creationImgRes.StatusCode === 5002) {
          wx.showToast({
            title: "生图失败,请重试",
            duration: 2000,
            icon: "error"
          })
        }
      }
    }
  },
  // 网络状态监听
  networkHandler(res) {
    console.log('网络', res)
    let msg = ''
    if (!res.isConnected) { // 无网络
      msg = '当前网络不可用，请检查你的网络设置'
      // _this.data.requestTask.offChunkReceived(this.serverResponse)
    } else if (res.networkType === 'none') {
      msg = '网络开小差了,请网络良好后重试'
      // _this.data.requestTask.offChunkReceived(this.serverResponse)
    }
    // 有网络
    if (res.isConnected) {
      // _this.initSSE()
      // _this.createImg()
    }
    if (msg) {
      wx.showToast({
        title: msg,
        icon: 'none',
      })
      return false
    }
  },
  // 画波浪1
  drawBall: function () {
    var canvas = {
      width: 305,
      height: 305,
    };
    var boHeight = canvas.height / 10;
    var posHeight = canvas.height / 1.2;
    //初始角度为0 
    var step = 0;
    //定义三条不同波浪的颜色 
    var lines = ["rgba(0,222,255, 0.2)",
      "rgba(157,192,249, 0.2)",
      "rgba(0,168,255, 0.2)"
    ];
    var context = wx.createContext();
    let requestAnimFrame = (function () {
      return function (callback) {
        setTimeout(callback, 1000 / 60);
      };
    })();

    function loop() {
      context.clearRect(0, 0, canvas.width, canvas.height);
      step++;
      //画3个不同颜色的矩形 
      for (var j = lines.length - 1; j >= 0; j--) {
        context.fillStyle = lines[j];
        //每个矩形的角度都不同，每个之间相差45度 
        var angle = (step + j * 50) * Math.PI / 180;
        var deltaHeight = Math.sin(angle) * boHeight;
        var deltaHeightRight = Math.cos(angle) * boHeight;
        context.beginPath();
        context.moveTo(0, posHeight + deltaHeight);
        context.bezierCurveTo(canvas.width / 2, posHeight + deltaHeight - boHeight, canvas.width / 2, posHeight + deltaHeightRight - boHeight, canvas.width, posHeight + deltaHeightRight);
        context.lineTo(canvas.width, canvas.height);
        context.lineTo(0, canvas.height);
        context.lineTo(0, posHeight + deltaHeight);
        context.closePath();
        context.fill();
      }
      wx.drawCanvas({
        canvasId: 'canvas',
        actions: context.getActions()
      })
      requestAnimFrame(loop);
    }
    loop();
  },
  // 画波浪2
  drawWave() {
    const ctx = wx.createCanvasContext('canvas');
    const width = 305; // canvas宽度  
    const height = 305; // canvas高度  
    const waveHeight = 20; // 波浪高度  
    const waveLength = 100; // 波浪长度  
    const waveCount = width / waveLength; // 波浪数量  

    // 绘制波浪  
    function drawWave() {
      ctx.beginPath();
      ctx.moveTo(0, height / 2);

      for (let i = 0; i < width; i += 1) {
        const x = i;
        const y = height / 2 + waveHeight * Math.sin(2 * Math.PI * i / waveLength + Math.PI / 2);
        ctx.lineTo(x, y);
      }

      ctx.lineTo(width, height); // 闭合路径（可选，根据需要）  
      ctx.lineTo(0, height);
      ctx.closePath();

      ctx.setStrokeStyle('blue');
      ctx.setLineWidth(2);
      ctx.stroke();
    }
    drawWave();
    ctx.draw();
  },
  onReady() {
    wx.createSelectorQuery().select("#top-header").boundingClientRect((rect) => {
      if (rect && rect.height) {
        this.setData({
          top: parseInt(rect.height)
        })
      }
    }).exec()
    wx.createSelectorQuery().select("#footer").boundingClientRect((rect) => {
      if (rect && rect.height) {
        this.setData({
          bottom: parseInt(rect.height)
        })
      }
    }).exec()
  },
  //生命周期函数--监听页面加载
  onLoad(options) {
    if (options) {
      this.setData({
        createtitle: options.createtitle,
        spacetype: options.spacetype
      })
    }
    this.setData({
      imgListLength: wx.getStorageSync('drawingParameter').num,
      createImgInfo: wx.getStorageSync('createImgInfo')
    })
    this.initSSE() //连接SSE
    this.createImg() //创建生图任务
    wx.onNetworkStatusChange(this.networkHandler)
  },
  //生命周期函数--监听页面卸载
  onUnload() {
    console.log('监听页面卸载');
    this.data.requestTask.offChunkReceived(this.serverResponse)
    wx.onNetworkStatusChange(this.networkHandler) //关闭网络监听
    this.setData({
      timer: null
    })
    // console.log('页面销毁');
  }
})